package cn.echo.modules.sys.controller.sitecontroller;

import cn.echo.modules.sys.entity.Site;
import cn.echo.modules.sys.service.SiteService;
import com.github.pagehelper.Page;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.validation.Valid;

@Controller//成为组件让系统可以注入这个对象
@RequestMapping("site")
public class SiteController{

//    @Autowired//按照类型注入(装配)--自动找到实现了SiteService类
//    @Qualifier("service")
    @Autowired
    private SiteService siteService;

    //1:@Autowire 按照类型自动装配(接口找实现的类) 如果是类就找这个类
    //2:@Autowired@Qualifier("service")通过名字装配 保证@Qualifier("名字")和@Service("名字")名字相同

    //3:@Resource 先通过名字找找不到通过类型找

    //4:基本数据类型可以用@Value("")

    //控制反转的注解:
    //@Component @Controller @Service @Repository
    //依赖注入的注解:
    //@Autowire @Qualifier  @Resource @Value
//    @Scope("prototype") 在类配置对象的域 单例 多例 request session
//    初始化：@PostConstruct
//    销毁：@PreDestroy
//            = new SiteService();

    @RequestMapping(value = {"list",""},method = RequestMethod.GET)
    public String list(@RequestParam(required = false,defaultValue = "1") Integer pageNum,
                       @RequestParam(required = false,defaultValue = "10") Integer pageSize,
                       Model model){
        //赋值页面页码大小自动帮我们计算，我们只需要在页面上使用PageInfo的数据就行
        PageHelper.startPage(pageNum,pageSize);
        Page<Site> siteList = (Page) siteService.findAll(new Site());
        //分页信息
        PageInfo<Site> pageInfo = new PageInfo(siteList);
        model.addAttribute("page",pageInfo);
        return "sys/site/sitelist";
    }
    @RequestMapping(value="toupdate",method = RequestMethod.GET)
    public String toUpdate(String id,Model model){
        Site site = siteService.findById(new Site(id));
        model.addAttribute("site",site);
        return "sys/site/siteupdate";
    }
    @RequestMapping(value = "update",method = RequestMethod.POST)
    public String update(@Valid Site site, BindingResult result){
        boolean flag = siteService.update(site);
        System.out.println("@@@@@update");
        if(result.hasErrors()){
            System.out.println("@@@result:"+result.getModel());
        }

        return "redirect:list";
    }
}
